package logic

import (
	"context"
	"errors"
	"hema-fresh-api/models/mysql"

	"hema-fresh-api/hema/hema"
	"hema-fresh-api/hema/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type HemaCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHemaCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HemaCreateLogic {
	return &HemaCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 创建
func (l *HemaCreateLogic) HemaCreate(in *hema.HemaCreateRequest) (*hema.HemaCreateResponse, error) {
	// todo: add your logic here and delete this line

	var name mysql.Hema

	begin := mysql.DB.Begin()

	if err := name.FindHemaByName(begin, in.Name); err == nil {
		return nil, errors.New("商品已存在")
	}
	if name.ID != 0 {
		return nil, errors.New("当前商品已存在")
	}

	var status mysql.Status

	if err := status.FindStatusByName(begin, in.StatusName); err != nil {
		status = mysql.Status{
			Name: in.StatusName,
		}
		if err := status.StatusAdd(begin); err != nil {
			begin.Rollback()
			return nil, errors.New("分类已存在，添加失败")
		}
	}

	Hema := mysql.Hema{
		Model:    gorm.Model{},
		Name:     in.Name,
		Image:    in.Image,
		Price:    float64(in.Price),
		StatusId: int64(status.ID),
	}
	err := Hema.HemaAdd(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}

	begin.Commit()

	return &hema.HemaCreateResponse{
		HemaId: int64(Hema.ID),
	}, nil
}
